package base.web.tools;

import com.opensymphony.xwork2.ActionContext;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * <ol>
 * date:11-3-10 editor:yanghongjian
 * <li>创建文档</li>
 * <li>对象或者集合封装成JSON格式及输出辅助类</li>
 * <li>从request中获取表单数据</li>
 * </ol>
 * <ol>
 *
 * @author <a href="mailto:yanghongjian@htjs.net">YangHongJian</a>
 * @version 2.0
 * @since 1.4.2
 */
public final class JsonHelp {
    private static Logger log = Logger.getLogger(JsonHelp.class);
    private static JSONObject jsonObject = new JSONObject();

    public JsonHelp() {
    }

    public static Map getSession() {
//        return (HttpSession) ActionContext.getContext().get(ServletActionContext.SESSION);
        return ActionContext.getContext().getSession();
    }


    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
    }

    public static HttpServletResponse getResponse() {
        return (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
    }

    public static Object getSessionAttribute(String key) {
        return getSession().get(key);
    }

    public static void setSessionAttribute(String key, Object obj) {
        getSession().put(key, obj);
    }

    public static boolean isEmpty(Object obj) {
        return obj == null || obj.equals("");
    }

    /**
     * 生成流水号
     *
     * @return 流水号
     */
    public static String getSeq() {
        String xh;
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("MMddhh");
        xh = df.format(date);
        int b = (int) (Math.random() * 8999 + 1000);//产生1000-9999的整数随机数

        return (xh + String.valueOf(b));
    }

    /**
     * 复制map对象中的值
     *
     * @param map    接受第二个参数中map的值
     * @param mapAdd 需要取值的map对象
     */
    public static void mapCopy(Map map, Map mapAdd) {
        if (map == null)
            map = new HashMap();
        if (mapAdd == null)
            return;

        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            map.put(key, mapAdd.get(key) != null ? (String) mapAdd.get(key) : "");
        }
    }

    /**
     * 通过子表的字段值生成map对象并把map对象保存到list对象中<br/>
     * <b>请注意:</b>参数中一定要XH键
     *
     * @param mapSubTab 子表map对象中的值是以","隔开的字符串
     * @param keys      关键字
     * @return 返回map集合对象
     */
    public static List createListByMap(Map mapSubTab, String keys) {
        List list = new ArrayList();
        String[] xh = ((String) mapSubTab.get(keys)).split(",", -1);
        for (int i = 0; i < xh.length; i++) {
            Map mapTem = new HashMap();
            Iterator it = mapSubTab.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                String val = (String) entry.getValue();
                String[] vals = val.split(",", -1);
                if (vals.length < xh.length)
                    mapTem.put(key, val);
                else {
                    mapTem.put(key, vals[i]);
                }
            }
            list.add(mapTem);
        }

        return list;
    }

    /**
     * 通过子表的字段值生成map对象并把map对象保存到list对象中<br/>
     * <b>请注意:</b>参数中一定要XH键
     *
     * @param mapSubTab 子表map对象中的值是以","隔开的字符串
     * @return 返回map集合对象
     */
    public static List createListByMap(Map mapSubTab) {
        List list = new ArrayList();
        String[] xh = ((String) mapSubTab.get("XH")).split(",", -1);
        for (int i = 0; i < xh.length; i++) {
            Map mapTem = new HashMap();
            Iterator it = mapSubTab.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                String val = (String) entry.getValue();
                String[] vals = val.split(",", -1);
                if (vals.length < xh.length)
                    mapTem.put(key, val);
                else {
                    if (key.equals("XH")) {//对空白序号自动生成序号

                        mapTem.put(key, vals[i].length() == 0 ? JsonHelp.getSeq() : vals[i]);
                    } else
                        mapTem.put(key, vals[i]);
                }
            }
            list.add(mapTem);
        }

        return list;
    }

    public static Map getReqParamMapGBK() {
        Map retMap = new HashMap();
        String val = "";
        for (Iterator it = getRequest().getParameterMap().entrySet().iterator(); it.hasNext(); ) {
            Map.Entry element = (Map.Entry) it.next();
            Object strKey = element.getKey();
            String[] value = (String[]) element.getValue();
            val = "";
            for (int i = 0; i < value.length; i++)
                val += value[i] + ',';
            val = val.substring(0, val.length() - 1);
            retMap.put(strKey, val);
        }
        return retMap;
    }

    public static Map getReqParamMapISO() {
        Map retMap = new HashMap();
        String val = "";
        for (Iterator it = getRequest().getParameterMap().entrySet().iterator(); it.hasNext(); ) {
            Map.Entry element = (Map.Entry) it.next();
            Object strKey = element.getKey();
            String[] value = (String[]) element.getValue();
            val = "";
            for (int i = 0; i < value.length; i++)
                val += JsonHelp.reconvert(value[i]) + ',';
            val = val.substring(0, val.length() - 1);
            retMap.put(strKey, val);
        }
        return retMap;
    }

    public static String getReqParamVal(String paramName) {
        List list = new ArrayList();
        try {
            list = Arrays.asList((String[]) getRequest().getParameterMap().get(paramName));
        } catch (NullPointerException e) {
//            log.error("读取参数->" + paramName + "=" + e.getMessage());
        }
        String val = "";
        for (int i = 0; i < list.size(); i++)
            val += (String) list.get(i) + ',';

        return val.length() > 0 ? (val.substring(0, val.length() - 1)) : val;
    }
//    public static String getReqParamValGBK(String paramName) {
//        List list = new ArrayList();
//        try {
//            list = Arrays.asList((String[]) getRequest().getParameterMap().get(paramName));
//        } catch (NullPointerException e) {
//            log.error("读取参数->" + paramName + "值时出错:" + e.getMessage());
//        }
//        String val = "";
//        for (int i = 0; i < list.size(); i++)
//            val += (String) list.get(i) + ',';
//
//        return val.length() > 0 ? (val.substring(0, val.length() - 1)) : val;
//    }

    /**
     * 获取提交参数对应的值
     *
     * @param paramName 提交的参数名
     * @return 返回参数对应的值, 注意参数名有相同时返回以","号隔开的字符串
     */
//    public static String getReqParamValISO(String paramName) {
//        List list = new ArrayList();
//        try {
//            list = Arrays.asList((String[]) getRequest().getParameterMap().get(paramName));
//        } catch (NullPointerException e) {
//            log.error("读取参数->" + paramName + "值时出错:" + e.getMessage());
//        }
//        String val = "";
//        for (int i = 0; i < list.size(); i++)
//            val += JsonHelp.reconvert((String) list.get(i)) + ',';
//
//        return val.length() > 0 ? (val.substring(0, val.length() - 1)) : val;
//    }

    /**
     * ajax请求返回
     *
     * @param retCode 返回代码
     * @param retInfo 返回消息
     */
    public static void ajaxResponseTxt(int retCode, String retInfo) {
        Map map = new LinkedHashMap();
        map.put("data", "");
        ajaxResponseTxt(retCode, retInfo, map);
    }

    /**
     * ajax请求返回
     *
     * @param retCode 返回代码
     * @param retInfo 返回消息
     * @param map     简单的附加
     */
    public static void ajaxResponseTxt(int retCode, String retInfo, Map map) {
        List list = new ArrayList();
        list.add(map);
        ajaxResponseTxt(retCode, retInfo, list);
    }

    /**
     * ajax请求返回
     *
     * @param retCode 返回代码
     * @param retInfo 返回消息
     * @param listMap 是HashMap类型的集合封装需要转化成JSON字符串的值对
     */
    public static void ajaxResponseTxt(int retCode, String retInfo, List listMap) {
        HttpServletResponse response = getResponse();

        response.setHeader("Charset", "UTF-8");
        //返回的是txt文本文件
        response.setContentType("text/json;charset=UTF-8");
        jsonObject.clear();
        Map tempMap = new HashMap();
        tempMap.put("code", String.valueOf(retCode));
        tempMap.put("info", JsonHelp.reconvert(retInfo));
        jsonObject.putAll(tempMap);
        for (Iterator it = listMap.iterator(); it.hasNext(); ) {
            jsonObject.putAll((Map) it.next());
        }
//        log.info("原始数据:"+jsonObject.toString());
        String strJson = JsonHelp.convert(jsonObject.toString());
        String jsoncallback = JsonHelp.getReqParamVal("callback");
        strJson = jsoncallback.length() == 0 ? strJson : jsoncallback + "(" + strJson + ")";
        log.info(strJson);
        try {
            PrintWriter out = response.getWriter();
            out.write(strJson);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * ajax请求返回
     *
     * @param strRet 返回消息
     */
    public static void ajaxResponse(String strRet) {
        HttpServletResponse response = getResponse();

        response.setHeader("Charset", "UTF-8");
        //返回的是txt文本文件
        response.setContentType("text/json;charset=UTF-8");

        String strJson = JsonHelp.convert(strRet);
        String jsoncallback = JsonHelp.getReqParamVal("callback");
        strJson = jsoncallback.length() == 0 ? strJson : jsoncallback + "(" + strJson + ")";
        log.info(strJson);
        try {
            PrintWriter out = response.getWriter();
            out.write(strJson);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    public static String getMapByKey(Map mapParam, String key) {
        Object val = mapParam.get(key);
        if (val instanceof String)
            return val.toString();
        String retStr = "";
        if (val != null) {
            if (val instanceof Timestamp) //定义格式并转化成字符型日期格式
                retStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Timestamp(((Timestamp) val).getTime()));
            if (val instanceof java.sql.Date) //定义格式并转化成字符型日期格式
                retStr = (new SimpleDateFormat("yyyy-MM-dd")).format(val);
            if (val instanceof BigDecimal)
                retStr = val.toString();
        }
        return retStr;
    }

    public static String createJsonString(int retCode, String retInfo) {
        return createJsonString(retCode, retInfo, new HashMap());
    }

    public static String createJsonString(int retCode, String retInfo, Map map) {
        List list = new ArrayList();
        list.add(map);
        return createJsonString(retCode, retInfo, list);
    }

    public static String createJsonString(int retCode, String retInfo, List listHashMap) {
        jsonObject.clear();
        Map tempMap = new HashMap();
        tempMap.put("code", String.valueOf(retCode));
        tempMap.put("info", JsonHelp.reconvert(retInfo));
        jsonObject.putAll(tempMap);
        for (Iterator it = listHashMap.iterator(); it.hasNext(); ) {
            jsonObject.putAll((Map) it.next());
        }
        //设定日期转换格式
//        JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
//        log.info("原始数据:"+jsonObject.toString());
        return JsonHelp.convert(jsonObject.toString());
    }

    /**
     * ===================================字符串处理结束===============//
     * ================================字符串编码转换开始===============//
     * 字符串编码转换为GBK
     *
     * @param str 被处理的字符串
     * @return String 将数据库中读出的数据进行转换
     */
    public static String convert(String str) {

        return str.trim();
//        String str1 = "";
//        if (str == null)
//            str = "";
//        str = str.trim();
//        if (str.length() > 0) {
//            try {
//                str1 = new String(str.getBytes("ISO8859_1"), "GBK");
//            } catch (Exception e) {
//                str1 = str;
//            }
//        }
//        return str1;
    }

    /**
     * 字符串编码反转换为ISO8859_1
     *
     * @param str 被处理的字符串
     * @return String 将jsp提交的数据进行转换放入数据库中
     */
    public static String reconvert(String str) {
        return str.trim();
//        String str1 = "";
//        if (str == null)
//            str = "";
//        str = str.trim();
//        if (str.length() > 0) {
//            try {
//                str1 = new String(str.getBytes("GBK"), "ISO8859_1");
//            } catch (Exception e) {
//                str1 = str;
//            }
//        }
//        return str1;
    }

    /**
     * 取得当前日期
     *
     * @param type 格式类型 0:yyyy-MM-dd 1:yyyy-MM-dd HH:mm:ss
     * @return String 返回当前年月日
     */
    public static String getCurStrDate(int type) {
        return (new SimpleDateFormat(type == 0 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm:ss")).format(new Date());
    }

    /**
     * 返回日期类型的值
     *
     * @param strDate 字符串类型日期
     * @param type    格式类型 0:yyyy-MM-dd 1:yyyy-MM-dd HH:mm:ss
     * @return 日期类型的值
     */
    public static Date getDateByStr(String strDate, int type) {
        type = strDate.length() == 10 ? 0 : 1;
        Date curDate = null;
        try {
            curDate = (new SimpleDateFormat(type == 0 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm:ss")).parse(strDate);

        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return curDate;
    }

    /**
     * 自定义时间显示方式
     *
     * @param type 类型<br>
     *             1 : yyyy-mm-dd<br>
     *             2 : yyyy-mm-dd hh:mm:ss<br>
     *             3 : yyyy年mm月dd日
     * @param date 日期
     * @return String <br>
     *         1: 返回yyyy-mm-dd<br>
     *         2: 返回yyyy-mm-dd hh:mm:ss<br>
     *         3: XXXX年XX月XX日
     */
    public static String getDateStr(Date date, int type) {
        if (date == null) return "";
        GregorianCalendar c = new GregorianCalendar();
        c.setTime(date);
        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH) + 1;
        int d = c.get(Calendar.DAY_OF_MONTH);
        int h = c.get(Calendar.HOUR_OF_DAY);
        int mi = c.get(Calendar.MINUTE);
        int s = c.get(Calendar.SECOND);

        String str = null;
        switch (type) {
            case 1:
                SimpleDateFormat b = new SimpleDateFormat("yyyy-MM-dd");
                str = b.format(date);
                // str = String.valueOf(y) + "-" + addStr(String.valueOf(m), "0", 2, true) + "-" + addStr(String.valueOf(d), "0", 2, true);
                break;
            case 2:
                SimpleDateFormat bb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                str = bb.format(date);
                break;
            case 3:
                SimpleDateFormat cc = new SimpleDateFormat("yyyy年MM月dd日");
                str = cc.format(date);
//                str = String.valueOf(y) + "年" + (m > 10 ? String.valueOf(m) : "0" + String.valueOf(m)) + "月" + (d > 10 ? String.valueOf(d) : "0" + String.valueOf(d)) + "日";
                break;
        }
        return str;
    }

    public static void main(String[] args) {
        JsonHelp.convert("中国");
    }
}
